import requests,time,re,json,random
import os
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import *
import tkinter.messagebox
import threading

TG_BOT_TOKEN = ""           # telegram bot token 自行申请
TG_USER_ID = ""             # telegram 用户ID
global now 
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 9; MI 6 MIUI/20.6.18)'
        }

#推送函数
def telegram_bot(title, content):
    try:
        tg_bot_token = TG_BOT_TOKEN
        tg_user_id = TG_USER_ID
        if "TG_BOT_TOKEN" in os.environ and "TG_USER_ID" in os.environ:
            tg_bot_token = os.environ["TG_BOT_TOKEN"]
            tg_user_id = os.environ["TG_USER_ID"]
        if not tg_bot_token or not tg_user_id:
            print("Telegram推送的TG_BOT_TOKEN或者TG_USER_ID未设置!!")
            return
        print("Telegram 推送开始")
        send_data = {"chat_id": tg_user_id, "text": title +
                     '\n\n'+content, "disable_web_page_preview": "true"}
        response = requests.post(
            url='https://api.telegram.org/bot%s/sendMessage' % (tg_bot_token), data=send_data)
        print(response.text)
    except:
        print("Error")
  
#获取登录code
def get_code(location):
    code_pattern = re.compile("(?<=access=).*?(?=&)")
    code = code_pattern.findall(location)[0]
    return code
  
#登录
def login(user,password):
    url1 = "https://api-user.huami.com/registrations/+86" + user + "/tokens"
    headers = {
        "Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",
    "User-Agent":"MiFit/4.6.0 (iPhone; iOS 14.0.1; Scale/2.00)"
        }
    data1 = {
        "client_id":"HuaMi",
        "password":f"{password}",
        "redirect_uri":"https://s3-us-west-2.amazonaws.com/hm-registration/successsignin.html",
        "token":"access"
        }
    r1 = requests.post(url1,data=data1,headers=headers,allow_redirects=False)
    location = r1.headers["Location"]
    try:
        code = get_code(location)
    except:
        return 0,0
    #print("access_code获取成功！")ste
    #print(code)
      
    url2 = "https://account.huami.com/v2/client/login"
    data2 = {
        "app_name":"com.xiaomi.hm.health",
        "app_version":"4.6.0",
        "code":f"{code}",
        "country_code":"CN",
        "device_id":"2C8B4939-0CCD-4E94-8CBA-CB8EA6E613A1",
        "device_model":"phone",
        "grant_type":"access_token",
        "third_name":"huami_phone",
        } 
    r2 = requests.post(url2,data=data2,headers=headers).json()
    login_token = r2["token_info"]["login_token"]
    #print("login_token获取成功！")
    #print(login_token)
    userid = r2["token_info"]["user_id"]
    #print("userid获取成功！")
    #print(userid)
  
    return login_token,userid
  
#主函数
def step_main(user, passwd, step, min_num, max_num):
    user = str(user)
    password = str(passwd)
    step = str(step)
    if user == '' or password == '':
        print ("用户名或密码填写有误！")
        return
     
    if step == '':
        print ("已设置为随机步数（"+str(min_num)+"-"+str(max_num)+"）")
        step = str(random.randint(min_num,max_num))
    login_token = 0
    login_token,userid = login(user,password)
    if login_token == 0:
        print("登陆失败！")
        return "login fail!"
  
    t = get_time()
      
    app_token = get_app_token(login_token)
  
    today = time.strftime("%F")
  
    data_json = '%5B%7B%22data_hr%22%3A%22%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F9L%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2FVv%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F0v%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F9e%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F0n%5C%2Fa%5C%2F%5C%2F%5C%2FS%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F0b%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F1FK%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2F%5C%2FR%5C%2F%5C%2F%5C%2F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fgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAAfgAA%22%2C%22tz%22%3A32%2C%22did%22%3A%22DA932FFFFE8816E7%22%2C%22src%22%3A24%7D%5D%2C%22summary%22%3A%22%7B%5C%22v%5C%22%3A6%2C%5C%22slp%5C%22%3A%7B%5C%22st%5C%22%3A1628296479%2C%5C%22ed%5C%22%3A1628296479%2C%5C%22dp%5C%22%3A0%2C%5C%22lt%5C%22%3A0%2C%5C%22wk%5C%22%3A0%2C%5C%22usrSt%5C%22%3A-1440%2C%5C%22usrEd%5C%22%3A-1440%2C%5C%22wc%5C%22%3A0%2C%5C%22is%5C%22%3A0%2C%5C%22lb%5C%22%3A0%2C%5C%22to%5C%22%3A0%2C%5C%22dt%5C%22%3A0%2C%5C%22rhr%5C%22%3A0%2C%5C%22ss%5C%22%3A0%7D%2C%5C%22stp%5C%22%3A%7B%5C%22ttl%5C%22%3A18272%2C%5C%22dis%5C%22%3A10627%2C%5C%22cal%5C%22%3A510%2C%5C%22wk%5C%22%3A41%2C%5C%22rn%5C%22%3A50%2C%5C%22runDist%5C%22%3A7654%2C%5C%22runCal%5C%22%3A397%2C%5C%22stage%5C%22%3A%5B%7B%5C%22start%5C%22%3A327%2C%5C%22stop%5C%22%3A341%2C%5C%22mode%5C%22%3A1%2C%5C%22dis%5C%22%3A481%2C%5C%22cal%5C%22%3A13%2C%5C%22step%5C%22%3A680%7D%2C%7B%5C%22start%5C%22%3A342%2C%5C%22stop%5C%22%3A367%2C%5C%22mode%5C%22%3A3%2C%5C%22dis%5C%22%3A2295%2C%5C%22cal%5C%22%3A95%2C%5C%22step%5C%22%3A2874%7D%2C%7B%5C%22start%5C%22%3A368%2C%5C%22stop%5C%22%3A377%2C%5C%22mode%5C%22%3A4%2C%5C%22dis%5C%22%3A1592%2C%5C%22cal%5C%22%3A88%2C%5C%22step%5C%22%3A1664%7D%2C%7B%5C%22start%5C%22%3A378%2C%5C%22stop%5C%22%3A386%2C%5C%22mode%5C%22%3A3%2C%5C%22dis%5C%22%3A1072%2C%5C%22cal%5C%22%3A51%2C%5C%22step%5C%22%3A1245%7D%2C%7B%5C%22start%5C%22%3A387%2C%5C%22stop%5C%22%3A393%2C%5C%22mode%5C%22%3A4%2C%5C%22dis%5C%22%3A1036%2C%5C%22cal%5C%22%3A57%2C%5C%22step%5C%22%3A1124%7D%2C%7B%5C%22start%5C%22%3A394%2C%5C%22stop%5C%22%3A398%2C%5C%22mode%5C%22%3A3%2C%5C%22dis%5C%22%3A488%2C%5C%22cal%5C%22%3A19%2C%5C%22step%5C%22%3A607%7D%2C%7B%5C%22start%5C%22%3A399%2C%5C%22stop%5C%22%3A414%2C%5C%22mode%5C%22%3A4%2C%5C%22dis%5C%22%3A2220%2C%5C%22cal%5C%22%3A120%2C%5C%22step%5C%22%3A2371%7D%2C%7B%5C%22start%5C%22%3A415%2C%5C%22stop%5C%22%3A427%2C%5C%22mode%5C%22%3A3%2C%5C%22dis%5C%22%3A1268%2C%5C%22cal%5C%22%3A59%2C%5C%22step%5C%22%3A1489%7D%2C%7B%5C%22start%5C%22%3A428%2C%5C%22stop%5C%22%3A433%2C%5C%22mode%5C%22%3A1%2C%5C%22dis%5C%22%3A152%2C%5C%22cal%5C%22%3A4%2C%5C%22step%5C%22%3A238%7D%2C%7B%5C%22start%5C%22%3A434%2C%5C%22stop%5C%22%3A444%2C%5C%22mode%5C%22%3A3%2C%5C%22dis%5C%22%3A2295%2C%5C%22cal%5C%22%3A95%2C%5C%22step%5C%22%3A2874%7D%2C%7B%5C%22start%5C%22%3A445%2C%5C%22stop%5C%22%3A455%2C%5C%22mode%5C%22%3A4%2C%5C%22dis%5C%22%3A1592%2C%5C%22cal%5C%22%3A88%2C%5C%22step%5C%22%3A1664%7D%2C%7B%5C%22start%5C%22%3A456%2C%5C%22stop%5C%22%3A466%2C%5C%22mode%5C%22%3A3%2C%5C%22dis%5C%22%3A1072%2C%5C%22cal%5C%22%3A51%2C%5C%22step%5C%22%3A1245%7D%2C%7B%5C%22start%5C%22%3A467%2C%5C%22stop%5C%22%3A477%2C%5C%22mode%5C%22%3A4%2C%5C%22dis%5C%22%3A1036%2C%5C%22cal%5C%22%3A57%2C%5C%22step%5C%22%3A1124%7D%2C%7B%5C%22start%5C%22%3A478%2C%5C%22stop%5C%22%3A488%2C%5C%22mode%5C%22%3A3%2C%5C%22dis%5C%22%3A488%2C%5C%22cal%5C%22%3A19%2C%5C%22step%5C%22%3A607%7D%2C%7B%5C%22start%5C%22%3A489%2C%5C%22stop%5C%22%3A499%2C%5C%22mode%5C%22%3A4%2C%5C%22dis%5C%22%3A2220%2C%5C%22cal%5C%22%3A120%2C%5C%22step%5C%22%3A2371%7D%2C%7B%5C%22start%5C%22%3A500%2C%5C%22stop%5C%22%3A511%2C%5C%22mode%5C%22%3A3%2C%5C%22dis%5C%22%3A1268%2C%5C%22cal%5C%22%3A59%2C%5C%22step%5C%22%3A1489%7D%2C%7B%5C%22start%5C%22%3A512%2C%5C%22stop%5C%22%3A522%2C%5C%22mode%5C%22%3A1%2C%5C%22dis%5C%22%3A152%2C%5C%22cal%5C%22%3A4%2C%5C%22step%5C%22%3A238%7D%5D%7D%2C%5C%22goal%5C%22%3A8000%2C%5C%22tz%5C%22%3A%5C%2228800%5C%22%7D%22%2C%22source%22%3A24%2C%22type%22%3A0%7D%5D'
  
    finddate = re.compile(r'.*?date%22%3A%22(.*?)%22%2C%22data.*?')
    findstep = re.compile(r'.*?ttl%5C%22%3A(.*?)%2C%5C%22dis.*?')
    data_json = re.sub(finddate.findall(data_json)[0], today, str(data_json))
    data_json = re.sub(findstep.findall(data_json)[0], step, str(data_json))
      
    url = f'https://api-mifit-cn.huami.com/v1/data/band_data.json?&t={t}'
    head = {
        "apptoken": app_token,
        "Content-Type": "application/x-www-form-urlencoded"
        }
      
    data = f'userid={userid}&last_sync_data_time=1597306380&device_type=0&last_deviceid=DA932FFFFE8816E7&data_json={data_json}'
     
    response = requests.post(url, data=data, headers=head).json()
    #print(response)
    result = f"{user[:3]}****{user[-4:]}: [{now}] 修改步数（{step}）"+ response['message']
    print(result)
    return result
   
#获取时间戳
def get_time():
    url = 'http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp'
    response = requests.get(url,headers=headers).json()
    t = response['data']['t']
    return t
   
#获取app_token
def get_app_token(login_token):
    url = f"https://account-cn.huami.com/v1/client/app_tokens?app_name=com.xiaomi.hm.health&dn=api-user.huami.com%2Capi-mifit.huami.com%2Capp-analytics.huami.com&login_token={login_token}"
    response = requests.get(url,headers=headers).json()
    app_token = response['token_info']['app_token']
    #print("app_token获取成功！")
    #print(app_token)
    return app_token
 
def gui_start():
    root=Tk()
    root.title("小米运动API")
    mainfram=Frame(root,width=320, height=660)
    mainfram.grid_propagate(0)
    mainfram.grid()
    
    labelName=tkinter.Label(root, text='用户名:', justify=tkinter.RIGHT, width=80)
    labelName.place(x=10, y=10, width=80, height=40)
    labelName=tkinter.Label(root, text='密码:', justify=tkinter.RIGHT, width=80)
    labelName.place(x=10, y=50, width=80, height=40)
    labelName=tkinter.Label(root, text='步数范围:', justify=tkinter.RIGHT, width=80)
    labelName.place(x=10, y=130, width=80, height=40)
    labelName=tkinter.Label(root, text='至', justify=tkinter.RIGHT, width=80)
    labelName.place(x=180, y=130, width=40, height=40)
    labelName=tkinter.Label(root, text='步数:', justify=tkinter.RIGHT, width=80)
    labelName.place(x=10, y=210, width=80, height=40)
    labelName=tkinter.Label(root, text='自动更新起始:', justify=tkinter.RIGHT, width=80)
    labelName.place(x=10, y=290, width=80, height=40)
    labelName=tkinter.Label(root, text='单次步数(N):', justify=tkinter.RIGHT, width=80)
    labelName.place(x=10, y=330, width=80, height=40)
    labelName=tkinter.Label(root, text='循环次数:', justify=tkinter.RIGHT, width=80)
    labelName.place(x=10, y=370, width=80, height=40)    
    labelName=tkinter.Label(root, text='BOT_TOKEN:', justify=tkinter.RIGHT, width=80)
    labelName.place(x=10, y=490, width=80, height=40) 
    labelName=tkinter.Label(root, text='USER_ID:', justify=tkinter.RIGHT, width=80)
    labelName.place(x=10, y=530, width=80, height=40) 

    user = ''
    passwd = ''
    step = ''
    user_list = []
    passwd_list = []
    setp_array = []
    push = ''
    auto_step = 0
    auto_loops = 1
    auto_solo = 6
    begin_step = 0
    end_step = 6
    min_num = 20000
    max_num = 29999
    global auto_flag
    auto_flag = 1
    global TG_flag
    TG_flag = 1
    
    f0 = open("steps.txt", 'a')
    f0.close()
    f1 = open("steps.txt", 'r')
    users=[]
    for line in f1.readlines():
        users.append(line)
    if len(users)>0:
        user = (users[0].split("\n")[0])
        if len(users)>1:
            passwd = (users[1].split("\n")[0])
    f1.close()
    
    e1 = Entry(mainfram)
    #e1.grid(ipadx=50,row=0,column=1)
    e1.delete(0, END)  # 将输入框里面的内容清空
    e1.insert(0, user)  
    e1.place(x=100, y=10, width=200, height=40)
    
    e2 = Entry(mainfram)
    #e2.grid(ipadx=50,row=1,column=1)
    e2.delete(0, END)  # 将输入框里面的内容清空
    e2.insert(0, passwd)
    e2.place(x=100, y=50, width=200, height=40)
    
    e3 = Entry(mainfram)
#    e3.grid(ipadx=50,row=3,column=0)
    e3.delete(0, END)  # 将输入框里面的内容清空
    e3.insert(0, "随机步数（"+str(min_num)+"-"+str(max_num)+"）") 
    e3.place(x=100, y=210, width=200, height=40)
    
    e4 = Entry(mainfram)
#    e3.grid(ipadx=50,row=3,column=0)
    e4.delete(0, END)  # 将输入框里面的内容清空
    e4.insert(0, str(min_num)) 
    e4.place(x=100, y=130, width=80, height=40)
    
    e5 = Entry(mainfram)
#    e3.grid(ipadx=50,row=3,column=0)
    e5.delete(0, END)  # 将输入框里面的内容清空
    e5.insert(0, str(max_num)) 
    e5.place(x=220, y=130, width=80, height=40)
    
    e6 = Entry(mainfram)
#    e3.grid(ipadx=50,row=3,column=0)
    e6.delete(0, END)  # 将输入框里面的内容清空
    e6.insert(0, str(begin_step)) 
    e6.place(x=100, y=290, width=200, height=40)
    
    e7 = Entry(mainfram)
#    e3.grid(ipadx=50,row=3,column=0)
    e7.delete(0, END)  # 将输入框里面的内容清空
    e7.insert(0, "默认为："+str(auto_loops)+"；约每N步/3s循环") 
    e7.place(x=100, y=370, width=200, height=40)
    
    e8 = Entry(mainfram)
#    e3.grid(ipadx=50,row=3,column=0)
    e8.delete(0, END)  # 将输入框里面的内容清空
    e8.insert(0, "默认为："+str(auto_solo)+"；20%随机浮动") 
    e8.place(x=100, y=330, width=200, height=40)
    
    e9 = Entry(mainfram)
#    e3.grid(ipadx=50,row=3,column=0)
    e9.delete(0, END)  # 将输入框里面的内容清空
    e9.insert(0, str(TG_BOT_TOKEN)) 
    e9.place(x=100, y=490, width=200, height=40)
    
    e10 = Entry(mainfram)
#    e3.grid(ipadx=50,row=3,column=0)
    e10.delete(0, END)  # 将输入框里面的内容清空
    e10.insert(0, str(TG_USER_ID)) 
    e10.place(x=100, y=530, width=200, height=40)
    
    def start():
        global TG_flag
        global now 
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        user = str(e1.get())
        passwd = str(e2.get())
        try:
            step = str(int(float(e3.get())))
        except:
            step = ""
        try:
            min_num_tem = int(float(e4.get()))
            max_num_tem = int(float(e5.get()))
            if min_num_tem < max_num_tem:
                min_num = int(min_num_tem)
                max_num = int(max_num_tem)
            else:
                min_num = 20000
                max_num = 29999
        except:
             min_num = 20000
             max_num = 29999
             
        e3.delete(0, END)  # 将输入框里面的内容清空
        e3.insert(0, str(step)) 
        
        if step == "":
            e3.delete(0, END)  # 将输入框里面的内容清空
            e3.insert(0, "随机步数（"+str(min_num)+"-"+str(max_num)+"）") 
            
        user_list = user.split('#')
        passwd_list = passwd.split('#')
        setp_array = step.split('-')
        
        if len(user_list) == len(passwd_list):
            push = ''
            for line in range(0,len(user_list)):
                if len(setp_array) == 2:
                    step = str(random.randint(int(setp_array[0]),int(setp_array[1])))
                elif str(step) == '0':
                    step = ''
                push += step_main(user_list[line], passwd_list[line], step, min_num, max_num) + '\n'
            if TG_flag == 0:
                thread2 = threading.Thread(target=telegram_bot("小米运动", push))
                thread2.start()
            else:
                TG_flag = 1
        else:
            print('用户名和密码数量不对')
            
    def save_user():
        user = str(e1.get())
        passwd = str(e2.get())
        
        f2 = open("steps.txt", 'w')
        f2.write(str(user))
        f2.write("\n")
        f2.write(str(passwd))
        f2.write("\n")
        f2.close()
        
    def save_random():        
        try:
            min_num_tem = int(float(e4.get()))
            max_num_tem = int(float(e5.get()))
            if min_num_tem < max_num_tem:
                min_num = int(min_num_tem)
                max_num = int(max_num_tem)
            else:
                min_num = 20000
                max_num = 29999
        except:
             min_num = 20000
             max_num = 29999

        e3.delete(0, END)  # 将输入框里面的内容清空
        e3.insert(0, "随机步数（"+str(min_num)+"-"+str(max_num)+"）") 
       
    def auto_steps():
        global auto_flag
        global TG_flag
        global now
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        time_flag = 0
        auto_flag = 0
        loop_flag = 0
        over_flag = 0
        one_step_time = 1
        loop_time_flag = 0
        time_over_flag = 0
        time_over_step = 0
        time_over_loop = 0
        first_time_flag = 0

        if auto_flag==0:
            try:
                auto_loops = int(float(e7.get()))
            except:
                auto_loops = 1
            print("循环总次数："+str(auto_loops))  
            try:
                begin_step = int(float(e6.get()))
            except:
                begin_step = 0
            print("起始步数："+str(begin_step))  
            try:
                auto_solo = int(float(e8.get()))
            except:
                auto_solo = 6
            random_step = random.randint(auto_solo-int(auto_solo/5),auto_solo+int(auto_solo/5))
            print("单次步数："+str(auto_solo-int(auto_solo/5))+"-"+str(auto_solo+int(auto_solo/5)))
            auto_step = begin_step
            end_step = auto_loops*auto_solo+begin_step
            print("预计更新步数："+str(begin_step)+"-"+str(end_step))
            print("预计所需时间："+str(int(auto_loops*3/3600))+"时"+str(int(((auto_loops*3/3600)%1)*60))+"分")
            user = str(e1.get())
            passwd = str(e2.get())
            user_list = user.split('#')
            passwd_list = passwd.split('#')
            
            time_over = time.time()
            begin_time = time.time()
            print("开始循环\n")
            while True:
                
                random_step = random.randint(auto_solo-int(auto_solo/5),auto_solo+int(auto_solo/5))
                auto_step = auto_step + random_step
                
                step = str(auto_step)
                setp_array = step.split('-')
                
                if len(user_list) == len(passwd_list):
                    push = ''
                    for line in range(0,len(user_list)):
                        if len(setp_array) == 2:
                            step = str(random.randint(int(setp_array[0]),int(setp_array[1])))
                        elif str(step) == '0':
                            step = ''
                        try:
                            push += step_main(user_list[line], passwd_list[line], step, min_num, max_num) + '\n'
                            if time_over_flag == 1:
                                if first_time_flag == 0:
                                    first_time_flag = 1
                                    over_flag = (time.time()-begin_time)/3
                                else:                                    
                                    over_flag = (time.time()-time_over)/one_step_time
                                time_over_step = int(over_flag*auto_solo)
                                time_flag = time_flag + int(over_flag)
                                time_over = time.time()
                                time_over_flag = 0
                                print("重置成功")
                            else:
                                time_over = time.time()
                                time_over_flag = 0
                        except:                            
                            time_over_flag = 1
                            time_flag = time_flag
                            loop_time_flag = time_flag+1
                            auto_step = auto_step - random_step
                            time.sleep(1)
                    if TG_flag == 0:
                        thread2 = threading.Thread(target=telegram_bot("小米运动", push))
                        thread2.start()
                    else:
                        TG_flag = 1
                else:
                    print('用户名和密码数量不对')
                    
                if time_over_flag == 1:
                    if time_over_loop == 0:
                        time_over_loop = time.time()
                        print("已断线，正在重置")
                    elif time.time() - time_over_loop > 30:
                        print("仍在断线中，请等待\n")
                        time_over_loop = 0
                else:
                    print("已自动更新步数："+str(auto_step)+"    完成度："+str(int(100*((auto_step-begin_step)/(end_step-begin_step))))+"%")
                    e3.delete(0, END)  # 将输入框里面的内容清空
                    e3.insert(0, str(auto_step)) 
                    loop_time_flag = time_flag+1
                    one_step_time = (time.time()-begin_time)/loop_time_flag
                    print("已循环次数："+str(loop_time_flag))
                    print("平均每步用时："+str(one_step_time))
                    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                    print("当前时间："+time.ctime()+"\n")
                    time.sleep(1)
                    if auto_flag == 1:
                        print("循环关闭")
                        print("自动更新结束\n")
                        return 0
                    if time_flag+1>=auto_loops:
                        print("已完成所有循环")
                        if auto_step < end_step:
                            print("正在补充剩余步数")
                            auto_step = end_step
                            step = str(auto_step)
                            setp_array = step.split('-')
                            while True:
                                try:
                                    push = ''+step_main(user_list[line], passwd_list[line], step, min_num, max_num) + '\n'
                                    print("已自动更新步数："+str(auto_step)+"    完成度："+str(int(100*((auto_step-begin_step)/(end_step-begin_step))))+"%")
                                    e3.delete(0, END)  # 将输入框里面的内容清空
                                    e3.insert(0, str(auto_step))
                                    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                                    print("当前时间："+time.ctime()+"\n")
                                    print("剩余步数补充完成")
                                    break
                                except:
                                    print("剩余步数补充失败，正在重试")
                                    time.sleep(1)
                                if auto_flag == 1:
                                    print("循环关闭")
                                    print("自动更新结束\n")
                                    return 0
                                else:
                                    auto_flag=0
                        print("自动更新结束\n")
                        return 0
                    else:
                        for j in range(time_flag+1,auto_loops):
                            if time_over_step > 0:
                                auto_step = auto_step + time_over_step
                                time_over_step = 0
                            else:
                                random_step = random.randint(auto_solo-int(auto_solo/5),auto_solo+int(auto_solo/5))
                                auto_step = auto_step + random_step
                            if auto_step > end_step:
                                auto_step = end_step
                            step = str(auto_step)
                            setp_array = step.split('-')
                            try:
                                push = ''+step_main(user_list[line], passwd_list[line], step, min_num, max_num) + '\n'
                                time_over = time.time()
                                time_over_flag = 0
                            except:
                                time_over_flag = 1
                                time_flag = j-1
                                auto_step = auto_step - random_step
                                print("已断线，正在重置")
                                break
                            if TG_flag == 0:
                                thread2 = threading.Thread(target=telegram_bot("小米运动", push))
                                thread2.start()
                            else:
                                TG_flag = 1
                            
                            print("已自动更新步数："+str(auto_step)+"    完成度："+str(int(100*((auto_step-begin_step)/(end_step-begin_step))))+"%")
                            e3.delete(0, END)  # 将输入框里面的内容清空
                            e3.insert(0, str(auto_step))
                            loop_time_flag = j+1
                            one_step_time = (time.time()-begin_time)/loop_time_flag
                            print("已循环次数："+str(loop_time_flag))
                            print("平均每步用时："+str(one_step_time))
                            now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                            print("当前时间："+time.ctime()+"\n")
                            if j+1 == auto_loops:
                                print("已完成所有循环")
                                if auto_step < end_step:
                                    print("正在补充剩余步数")
                                    auto_step = end_step
                                    step = str(auto_step)
                                    setp_array = step.split('-')
                                    while True:
                                        try:
                                            push = ''+step_main(user_list[line], passwd_list[line], step, min_num, max_num) + '\n'
                                            print("已自动更新步数："+str(auto_step)+"    完成度："+str(int(100*((auto_step-begin_step)/(end_step-begin_step))))+"%")
                                            e3.delete(0, END)  # 将输入框里面的内容清空
                                            e3.insert(0, str(auto_step))
                                            now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                                            print("当前时间："+time.ctime()+"\n")
                                            print("剩余步数补充完成")
                                            break
                                        except:
                                            print("剩余步数补充失败，正在重试")
                                            time.sleep(1)
                                        if auto_flag == 1:
                                            print("循环关闭")
                                            print("自动更新结束\n")
                                            return 0
                                        else:
                                            auto_flag=0
                                print("自动更新结束\n")
                                return 0
                            if auto_flag == 1:
                                print("循环关闭")
                                print("自动更新结束\n")
                                return 0
                            else:
                                auto_flag=0
                                time.sleep(1)
                    
                if loop_flag == 1:
                    print("已完成所有循环")
                    print("自动更新结束")
                    return 0
                if auto_flag == 1:
                    print("循环关闭")
                    print("自动更新结束\n")
                    return 0
            else:
                print("循环关闭")
                
            print("自动更新结束\n")
            return 0

    def start_thread():
        thread0 = threading.Thread(target=start)
        thread0.start()
        
    def auto_thread():
        global auto_flag
        auto_flag=0
        thread1 = threading.Thread(target=auto_steps)
        thread1.start() 
    
    def auto_close():
        global auto_flag
        auto_flag=1
        print("正在关闭自动更新")
        
    def TG_set():
        global TG_BOT_TOKEN
        global TG_USER_ID
        global TG_flag
        TG_flag=0
        TG_BOT_TOKEN=e9.get()
        TG_USER_ID=e10.get()
        print("已设置推送")
    
    def TG_close():
        global TG_BOT_TOKEN
        global TG_USER_ID
        global TG_flag
        TG_flag=1
        TG_BOT_TOKEN=""
        TG_USER_ID=""
        print("已关闭推送")
        
    button0=Button(mainfram,width=30,text="记住用户",command=save_user).place(x=100, y=90, width=200, height=40)
    button1=Button(mainfram,width=30,text="更新步数",command=start_thread).place(x=100, y=250, width=200, height=40)
    button2=Button(mainfram,width=30,text="更新随机步数范围显示",command=save_random).place(x=100, y=170, width=200, height=40)
    button3=Button(mainfram,width=30,text="开启步数自动更新",command=auto_thread).place(x=100, y=410, width=200, height=40)
    button4=Button(mainfram,width=30,text="关闭自动更新",command=auto_close).place(x=100, y=450, width=200, height=40)
    button5=Button(mainfram,width=30,text="设置推送",command=TG_set).place(x=100, y=570, width=200, height=40)
    button6=Button(mainfram,width=30,text="关闭推送",command=TG_close).place(x=100, y=610, width=200, height=40)
    
    root.mainloop()
    
def normal_start():
    # 用户名（单用户的格式为 13800138000 ，多用户用#隔开，例如13800138000#13800138000#13800138000）
    user = input("用户名：")
    # 登录密码（用#隔开，例如123456#123456#123456）
    if user == "":
        print("未登录用户")
        return 0
    passwd = input("密码：")
    # 要修改的步数，直接输入想要修改的步数值，留空为随机步数20000至29999之间
    if passwd == "":
        print("未登录用户")
        return 0
    step = input("步数（默认为20000-29999的随机数）：")
    
    min_num = 20000
    max_num = 29999
    
    user_list = user.split('#')
    passwd_list = passwd.split('#')
    setp_array = step.split('-')
    
    if len(user_list) == len(passwd_list):
        push = ''
        for line in range(0,len(user_list)):
            if len(setp_array) == 2:
                step = str(random.randint(int(setp_array[0]),int(setp_array[1])))
            elif str(step) == '0':
                step = ''
            push += step_main(user_list[line], passwd_list[line], step, min_num, max_num) + '\n'
        telegram_bot("小米运动", push)
    else:
        print('用户名和密码数量不对')

if __name__ ==  "__main__":
    print("已打开窗口")
    gui_start()
    print("已关闭窗口，并开启终端模式")
    while True:
        normal_start()
        normal_flag = input("是否继续(Y/N)？：")
        if normal_flag == "N":
            print("程序结束")
            break
        if normal_flag == "Y":
            print("程序继续")
        else:
            print("程序结束")
            break
    